﻿using System.Text.Json;
using TodayApp.Models;

namespace TodayApp.Services;

public class TodayPoetryService : ITodayPoetryService {
    private readonly IAlertService _alertService;

    private readonly IPreferenceStorage _preferenceStorage;

    public TodayPoetryService(IAlertService alertService,
        IPreferenceStorage preferenceStorage) {
        _alertService = alertService ??
            throw new ArgumentNullException(nameof(alertService));
        _preferenceStorage = preferenceStorage ??
            throw new ArgumentNullException(nameof(preferenceStorage));
    }

    private const string TokenKey = $"{nameof(TodayPoetryService)}.Token";

    public async Task<TodayPoetry> GetTodayPoetryAsync() {
        var httpClient = new HttpClient();

        HttpResponseMessage response;
        string json;

        if (string.IsNullOrWhiteSpace(
                _preferenceStorage.Get(TokenKey, string.Empty))) {
            try {
                response =
                    await httpClient.GetAsync(
                        "https://v2.jinrishici.com/token");
                response.EnsureSuccessStatusCode();
            } catch (Exception e) {
                _alertService.Alert(e.Message);
                return new TodayPoetry {Snippet = "无寻处，唯有少年心"};
            }

            json = await response.Content.ReadAsStringAsync();
            var tokenObject = JsonSerializer.Deserialize<Token>(json);
            _preferenceStorage.Set(TokenKey, tokenObject.data);
        }

        httpClient.DefaultRequestHeaders.Add("X-User-Token",
            _preferenceStorage.Get(TokenKey, string.Empty));
        try {
            response =
                await httpClient.GetAsync("https://v2.jinrishici.com/sentence");
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            _alertService.Alert(e.Message);
            return new TodayPoetry {Snippet = "无寻处，唯有少年心"};
        }

        json = await response.Content.ReadAsStringAsync();
        var sentenceObject = JsonSerializer.Deserialize<Sentence>(json);
        return new TodayPoetry {Snippet = sentenceObject.data.content};
    }
}

public class Token {
    public string data { get; set; }
}

public class Sentence {
    public Data data { get; set; }
}

public class Data {
    public string content { get; set; }
}